﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;

public partial class UpdateUserPwd : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["loginname"] != null)
            {
                this.txtName.Text = Server.HtmlEncode(Request.Cookies["loginname"].Value);
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        CMSModel.CMSEntities dal = DAL.DBManager.GetCmsEmtity();

        CMSModel.User user = dal.User.First(x => x.LoginName.Contains(txtName.Text));
        EncryptClasses.DESEncrypt des = new EncryptClasses.DESEncrypt();
        //string pwd = getMd5Hash(txtPwd.Text);
        try
        {
            string pwd = des.Decrypt(user.pwd.ToString());
            if (txtPwd.Text != pwd)
            {
                ClientScript.RegisterStartupScript(GetType(), "updatepwd", "alert('原始密码不正确')", true);
            }
            else
            {
                user.pwd = des.Encrypt(txtNPwd.Text);
                dal.SaveChanges();
                ClientScript.RegisterStartupScript(GetType(), "updatepwd", "alert('修改成功！')", true);
            }
        }
        catch (Exception ex)
        {
            LogYuMin.LogWriter.GetWriter(LogYuMin.LogFile.error).Write(GetType(), "updatePwd", LogYuMin.LogStates.ERROR, ex);
            ClientScript.RegisterStartupScript(GetType(), "updatepwd", "alert('修改失败！')", true);
        }
    }
    /// <summary>
    /// 加密字符串MD5
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    static string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }
}